//
//  DASearchBookViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/5/5.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DASearchBookViewController.h"
#import "DASearchBookTableViewCell.h"
#import "DATabBarViewController.h"
#import "DASearchBookDetailViewController.h"
#import "DASearchBookModel.h"
#import "DAFindBookTableViewCell.h"
@interface DASearchBookViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate,UISearchBarDelegate>{
    UIView *statusCover;
}

@property (strong, nonatomic) NSMutableArray *searchResults;

@property (weak, nonatomic) IBOutlet UISearchBar *search;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger pageNumber;
@property (nonatomic) BOOL isRefresh;
@property (nonatomic, strong) NSMutableArray *searchBookArray;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *searchController;

@property (nonatomic, assign) NSInteger findBookNumber;

@property (nonatomic) BOOL isSearchRefresh;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *footer;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *SearchFooter;


@end

@implementation DASearchBookViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F3F0ED"];
    [self searchSetting];
    [self prepareData];
    [self prepareDataSearchBook];
    [self tableViewSetting];
    [self.tableView.mj_header beginRefreshing];
    self.isRefresh = YES;
    self.pageNumber = 0;
    self.findBookNumber = 0;
    self.isSearchRefresh = YES;
}
#pragma mark - searchBar设置
- (void)searchSetting{
    self.search.backgroundImage = [self imageWithColor:[UIColor clearColor] size:self.search.bounds.size];
    NSString *input = NSLocalizedString(@"InputBookNameForSearch", nil);
    self.search.placeholder = input;
    self.search.delegate = self;
   // self.tableView.tableHeaderView = self.search;
    self.searchController.delegate = self;
    UITextField *text = [self.search valueForKey:@"_searchField"];
    [text setValue:[UIFont systemFontOfSize:12] forKeyPath:@"_placeholderLabel.font"];
    self.backView.backgroundColor = [UIColor colorWithHexString:@"#F3F0ED"];
    // 取消按钮的字体颜色
   // [self.search setTintColor:[UIColor whiteColor]];
    //[self.search setBarTintColor:[UIColor supportGreenColor]];

    [self.search setTintColor:[UIColor whiteColor]];
    [[[[self.searchController.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self.searchController.searchBar setBackgroundColor:[UIColor supportGreenColor]];
    statusCover = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 20)];
    statusCover.backgroundColor = [UIColor supportGreenColor];
    [self.view addSubview:statusCover];
    [self.search setTintColor:[UIColor whiteColor]];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.searchController.searchBar setBackgroundColor:[UIColor colorWithHexString:backGroundColor]];
    [statusCover removeFromSuperview];
    [self.search setTintColor:[UIColor darkGrayColor]];
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(nullable NSString *)searchString{
    [self.searchResults removeAllObjects];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bookName contains[cd] %@", self.search.text];
    NSLog(@"关键字 %@",self.search.text);
    self.searchResults = [[self.dataArray filteredArrayUsingPredicate:predicate]mutableCopy];
    NSLog(@"Search %@", self.searchResults);
    
    //  [self.tableVIew reloadData];
    [self.searchDisplayController.searchResultsTableView reloadData];
    
    return YES;
}
- (void)dealloc{
    self.tableView.delegate = nil;
    self.search.delegate = nil;
}
#pragma mark -tableView 设置
- (void)tableViewSetting{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = 100;
    self.searchController.delegate = self;
    self.searchController.searchResultsTableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    // 下拉
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
    
    // 上拉
    self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = self.footer;
    self.tableView.mj_footer.hidden = YES;

    // 注册cell
    [self.searchController.searchResultsTableView registerClass:[DAFindBookTableViewCell class] forCellReuseIdentifier:@"findBook"];
    
    // 上拉
  //  self.searchController.searchResultsTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(findMoreBook)];
    // self.searchBookArray  =[NSMutableArray array];
    // self.searchController.searchResultsTableView.tableFooterView = [UIView new];
    
    // 调用搜索的tableView的MJ刷新
    [self searchControllerMJ];
}
#pragma mark - 给搜索的tableView添加MJ刷新
- (void)searchControllerMJ{
       // 上拉
    self.SearchFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreSearchData)];
    
    self.searchController.searchResultsTableView.mj_footer = self.SearchFooter;
    self.searchController.searchResultsTableView.mj_footer.hidden = YES;
    
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshSearchData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    //self.tableView.mj_header = header;
    self.searchController.searchResultsTableView.mj_header = header;
    
    self.searchController.searchResultsTableView.tableFooterView = [UIView new];
   // self.searchController.searchResultsTableView.subviews[6].backgroundColor = [UIColor whiteColor];
    
//    for (UIView *view in self.searchController.searchResultsTableView.subviews) {
//        if ([view isKindOfClass:NSClassFromString(@"_UISearchBarShadowView")]) {
//           // [view removeFromSuperview];
//            view.backgroundColor = [UIColor whiteColor];
//            
//        }
//    }
}
#pragma mark - 下拉刷新
- (void)refreshData{
    self.isRefresh = YES;
    self.pageNumber = 0;
    [self prepareData];
}
#pragma mark - 上拉
- (void)loadMoreData{
    self.isRefresh = NO;
    [self prepareData];
}
#pragma mark - 数据准备
- (void)prepareData{
    NSString *url = DABookListURL;
    NSString *pageNumber = [NSString stringWithFormat:@"%ld", (long)self.pageNumber];
    NSDictionary *dic = @{@"typeID" : self.typeID,
                          @"page": pageNumber};
    NSLog(@"%ld", (long)self.pageNumber);
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if (result[@"result"] != nil && [result[@"result"] isKindOfClass:[NSArray class]]) {
            [self.tableView.mj_header endRefreshing];
            NSLog(@"%ld", [result[@"result"] count]);
            if ([result[@"result"] count] > 0) {
                
                if ([result[@"result"] count] < 20) {
                   // self.footer.stateLabel.hidden = YES;
                    self.tableView.mj_footer.hidden = YES;
                }else{
                  //  self.footer.stateLabel.hidden = NO;
                    self.tableView.mj_footer.hidden = NO;
                }
            
                DASearchBookDetailModel *searchModel = [[DASearchBookDetailModel alloc]init];
                NSArray *array  =   [searchModel returnModelInArrayWithArray:result[@"result"]];
                if (self.isRefresh) {
                    self.dataArray  = [NSMutableArray array];
                    [self.dataArray addObjectsFromArray:array];
                    [self.tableView reloadData];
                    [self.tableView.mj_header endRefreshing];
                }else{
                    [self.dataArray addObjectsFromArray:array];
                    [self.tableView reloadData];
                    [self.tableView.mj_footer endRefreshing];
                    
                }
                self.pageNumber++;
            }
        } else {
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"]isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                
            }else if([result[@"result"] isKindOfClass:[NSArray class]] && [result[@"result"] count] == 0) {
                NSLog(@"没有更多数据 %ld", (long)self.pageNumber);
                
            }else{                
                NSLog(@"DABookListURL:数据异常。");
            }
        
        }
        [self.tableView.mj_footer endRefreshing];
        
    }];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"搜索");
    [self prepareDataSearchBook];
}
#pragma mark - 搜索的上拉
- (void)findMoreBook{
    [self prepareDataSearchBook];
}

#pragma mark - 搜索的tableView 上拉加载
- (void)loadMoreSearchData{
    self.isSearchRefresh = NO;
    [self prepareDataSearchBook];
}
#pragma mark - 搜索的tableView 下拉刷新
- (void)refreshSearchData{
    self.isSearchRefresh = YES;
    self.findBookNumber = 0;
    [self prepareDataSearchBook];
}
#pragma mark - 图书搜索
- (void)prepareDataSearchBook{
    NSString *url = DASearchBookURL;
    NSString *pageNumber = [NSString stringWithFormat:@"%ld", (long)self.findBookNumber];
    NSDictionary *dic = @{@"keyword": self.search.text,
                          @"page": pageNumber};
    NSLog(@"%ld", (long)self.findBookNumber);
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]]) {
            if ([result[@"result"] count] < 20) {
                //self.SearchFooter.stateLabel.hidden = YES;
                self.searchController.searchResultsTableView.mj_footer.hidden = YES;
            }else{
                //self.SearchFooter.stateLabel.hidden = NO;
                self.searchController.searchResultsTableView.mj_footer.hidden = YES;
            }
            if ([result[@"result"] count] > 0) {
                [self dataTransformModel:result[@"result"]];
                self.findBookNumber++;
            }else{
                if (self.isSearchRefresh) {
                    [self.searchController.searchResultsTableView.mj_header endRefreshing];
                }else{
                    [self.searchController.searchResultsTableView.mj_footer endRefreshing];
                }
                
                if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                    [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                }
                if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                    [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
                }
                if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                    [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
                }
                
                
                NSLog(@"没有更多数据");
            }
        }else{
            
        }
        NSLog(@"%@", result);
    }];
}
#pragma mark - Model转化
- (void)dataTransformModel:(NSArray *)dataArray{
    DASearchBookModel  *searchBookModel = [[DASearchBookModel alloc]init];
    NSArray *array = [searchBookModel returnModelInArrayWithDic:dataArray];
    if (self.isRefresh) {
        self.searchBookArray = [NSMutableArray array];
        [self.searchBookArray addObjectsFromArray:array];
        [self.searchController.searchResultsTableView reloadData];
        [self.searchController.searchResultsTableView.mj_header endRefreshing];
    }else{
        [self.searchBookArray addObjectsFromArray:array];
        [self.searchController.searchResultsTableView.mj_footer endRefreshing];
    }
    NSLog(@"searchBook %@",self.searchBookArray);
}
#pragma mark - search协议方法
//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
//    self.findBookNumber = 0;
//    self.isSearchRefresh = YES;
//    NSLog(@"%ld", (long)self.findBookNumber);
//    [self.searchBookArray removeAllObjects];
//    return YES;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        return self.dataArray.count;
    }else{
        return self.searchResults.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
         DASearchBookTableViewCell *search = [tableView dequeueReusableCellWithIdentifier:@"search"];
        search.searchModel = self.dataArray[indexPath.row];
        return search;
    }else{
        DAFindBookTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"findBook"];
        if (self.searchBookArray.count > 0) {
            cell.searchModel = self.searchResults[indexPath.row];
        }
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView) {
        return 100;
    }else{
        return 100;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        DASearchBookDetailViewController *detailVC = [story instantiateViewControllerWithIdentifier:@"SEARCHBOOKDETAIL"];
      //  detailVC.bookDetailModel = self.dataArray[indexPath.row];
        detailVC.bookID = [self.dataArray[indexPath.row] bookID];
        detailVC.isHomePageEnter = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }else{
        DASearchBookDetailViewController *searchDetail = [self.storyboard instantiateViewControllerWithIdentifier:@"SEARCHBOOKDETAIL"];
        searchDetail.bookID = [self.searchBookArray[indexPath.row] bookID];
        searchDetail.isHomePageEnter = YES;
        [self.navigationController pushViewController:searchDetail animated:YES];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
#pragma mark - searchBar背景颜色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - 解决UISearchDisplayController searchResultsTableView 的ContentSize bug
- (void)searchDisplaycontroller:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 解决UISearchDisplayController searchResultsTableView 的ContentSize bug
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
